const PENDING = "PENDING";
const FULFILLED = "FULFILLED";
const REJECTED = "REJECTED";

class Promise {
  constructor(executor) {
    // 让promise变成成功态
    this.status = PENDING; // 默认为等待态
    this.value = undefined; // 为什么成功
    this.reason = undefined; // 为什么失败
    this.onResolvedCallbacks = []; // 存放成功的回调列表
    this.onRejectedCallbacks = []; // 存放失败的回调列表
    const resolve = (value) => {
      if (this.status === PENDING) {
        this.value = value;
        this.status = FULFILLED;
        // 发布
        this.onResolvedCallbacks.forEach((fn) => fn());
      }
    };
    // 让promise变成失败态
    const reject = (reason) => {
      if (this.status === PENDING) {
        this.reason = reason;
        this.status = REJECTED;
        this.onRejectedCallbacks.forEach((fn) => fn());
      }
    };
    try {
      executor(resolve, reject);
    } catch (e) {
      reject(e);
    }
  }
  then(onFulfilled, onRejected) {
    if (this.status === FULFILLED) {
      onFulfilled(this.value);
    }
    if (this.status === REJECTED) {
      onRejected(this.reason);
    }
    if (this.status === PENDING) {
      // 订阅模式
      this.onResolvedCallbacks.push(() => {
        // 额外的扩展
        onFulfilled(this.value);
      });
      this.onRejectedCallbacks.push(() => {
        onRejected(this.reason);
      });
    }
  }
}
export default Promise;
